package com.yhsimon.syn;

public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(1000, "成长基金");
        Bank you=new Bank(account,50,"你");
        Bank girlFriend=new Bank(account, 100,"girlFriend");

        you.start();
        girlFriend.start();
    }
}

//账户
class Account {
    int money;
    String name;

    public Account(int money,String name){
        this.money=money;
        this.name=name;
    }
}


//银行：模拟取款
class Bank extends Thread{
    Account account;
    int drawingMoney; //取了多少钱
    int curMoney;     //现在手里有多少钱

    public Bank(Account account,int drawingMoney,String name){
        super(name);
        this.account=account;
        this.drawingMoney=drawingMoney;
    }

    //取钱
    //synchronized (本身)
    @Override
    public  void run() {
        synchronized (account){
            if(account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+" 余额不足，无法取款");
                return;
            }

            //sleep可以放大问题的发生性
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //卡内余额
            account.money-=drawingMoney;
            //你手里的钱
            curMoney+=drawingMoney;

            System.out.println(account.name+"余额为："+account.money);

//        Thread.currentThread().getName()=this.getName();
            System.out.println(this.getName()+"手里的钱："+curMoney);
        }
    }
}